package wsi.gui.detector;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.rygh.core.face.IDone;
import org.rygh.core.util.timer.TaskTime;
import org.rygh.core.util.timer.TaskTimeManager;
import org.rygh.gui.swing.component.SWorker;
import org.rygh.semantic.gui.swing.input.Input;

import wsi.detect.DetectHelper;
import wsi.function.Function;
import wsi.match.SubtreeMatch;
import wsi.subgraph.tree.EntityTree;

@Deprecated
public class DetectWorker extends SWorker<List<DetectorTuple>, Void> {

	private final List<Input> inputs;
	private final Function function;
	private final int inputSize;
	private int webcalls;

	private TaskTimeManager timeManager;

	public DetectWorker(IDone master, List<Input> inputs, Function function,
			int inputSize) {
		super(master);

		this.inputs = inputs;
		this.function = function;
		this.inputSize = inputSize;
	}

	/**
	 * check if there is a valid entity tree first, then call web.
	 * 
	 * @return
	 */
	public List<DetectorTuple> compute() {

		System.out.printf("detecting for %d inputs\n", inputSize);

		List<DetectorTuple> tuples = new ArrayList<>();

		DetectorTuple tuple;
		String result;

		DetectHelper detector = new DetectHelper();
		SubtreeMatch sm;

		int id = 1, c = inputs.size(), match_count;

		webcalls = 0;
		setProgress(0);

		for (int i = 0; i < c && tuples.size() < inputSize; i++) {
			if (isCancelled())
				break;

			setProgress(100 * tuples.size() / inputSize);

			Input input = inputs.get(i);
			int degree = input.getEntity().getDegree();

			if (timeManager != null) {
				TaskTime timer = timeManager.newTask(input.getEntity()
						.getValue());
				detector.setTimer(timer);
			}

			// check if there is a valid tree

			EntityTree ent_tree = detector.prepareTree(input, function);

			if (ent_tree == null)
				continue;

			webcalls++;
			result = detector.prepareHtml(input, function);

			if (result == null)
				continue;

			sm = detector.detect(input, ent_tree, result);

			if (sm == null)
				continue;

			match_count = sm.size();
			System.out.printf(
					"[info] degree %d, match count %d, tuple size %d/%d\n",
					degree, match_count, tuples.size(), inputSize);

			if (match_count > 0) {
				tuple = new DetectorTuple(id++, input);
				tuple.setDegree(degree);
				tuple.setMatchCount(match_count);
				tuple.setWebCalls(webcalls);
				tuples.add(tuple);
			}
		}

		// write web calls info

		Collections.sort(tuples);

		setProgress(100);
		return tuples;
	}

	@Override
	protected List<DetectorTuple> doInBackground() throws Exception {
		return compute();
	}

	public int getWebcalls() {
		return webcalls;
	}

	public void setTimeManager(TaskTimeManager timeManager) {
		this.timeManager = timeManager;
	}

}
